#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
配置管理模块
用于保存和加载用户配置信息
"""

import os
import json
import time

class ConfigManager:
    """配置管理类"""
    
    def __init__(self):
        """初始化配置管理器"""
        # 配置文件路径
        self.config_dir = os.path.join(os.path.expanduser('~'), '.cegui_editor')
        self.config_file = os.path.join(self.config_dir, 'config.json')
        
        # 默认配置
        self.default_config = {
            'root_directory': '',
            'imageset_search_dir': '',
            'last_layout_file': '',
            'recent_layouts': [],
            'processed_layouts': {},  # 新增：记录已处理的布局文件
            'window_geometry': {
                'x': 100,
                'y': 100,
                'width': 1200,
                'height': 800
            },
            'preview_resolution': {
                'width': 800,
                'height': 600
            },
            'last_update_time': time.time()
        }
        
        # 当前配置
        self.config = self.default_config.copy()
        
        # 确保配置目录存在
        self._ensure_config_dir()
        
        # 加载配置
        self.load_config()
    
    def _ensure_config_dir(self):
        """确保配置目录存在"""
        if not os.path.exists(self.config_dir):
            try:
                os.makedirs(self.config_dir)
            except Exception as e:
                print(f"创建配置目录失败: {e}")
    
    def load_config(self):
        """加载配置"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    # 更新配置，保留默认值
                    for key, value in loaded_config.items():
                        if key in self.config:
                            self.config[key] = value
            except Exception as e:
                print(f"加载配置文件失败: {e}")
    
    def save_config(self):
        """保存配置"""
        try:
            # 更新时间戳
            self.config['last_update_time'] = time.time()
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, ensure_ascii=False, indent=4)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def get(self, key, default=None):
        """获取配置项"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置项"""
        if key in self.config:
            self.config[key] = value
            return True
        return False
    
    def set_root_directory(self, directory):
        """设置工程根目录"""
        self.config['root_directory'] = directory
        self.save_config()
    
    def set_imageset_search_dir(self, directory):
        """设置Imageset搜索目录"""
        self.config['imageset_search_dir'] = directory
        self.save_config()
    
    def set_last_layout_file(self, file_path):
        """设置最后打开的布局文件"""
        self.config['last_layout_file'] = file_path
        
        # 更新最近打开的文件列表
        recent_layouts = self.config['recent_layouts']
        if file_path in recent_layouts:
            recent_layouts.remove(file_path)
        recent_layouts.insert(0, file_path)
        
        # 最多保存10个最近文件
        self.config['recent_layouts'] = recent_layouts[:10]
        self.save_config()
    
    def set_window_geometry(self, x, y, width, height):
        """设置窗口几何信息"""
        self.config['window_geometry'] = {
            'x': x,
            'y': y,
            'width': width,
            'height': height
        }
        self.save_config()
    
    def set_preview_resolution(self, width, height):
        """设置预览分辨率"""
        self.config['preview_resolution'] = {
            'width': width,
            'height': height
        }
        self.save_config()
        
    def set_last_imageset_file(self, file_path):
        """设置最后加载的Imageset文件"""
        self.config['last_imageset_file'] = file_path
        
        # 更新最近加载的图集文件列表
        recent_imagesets = self.config.get('recent_imagesets', [])
        if file_path in recent_imagesets:
            recent_imagesets.remove(file_path)
        recent_imagesets.insert(0, file_path)
        
        # 最多保存10个最近图集文件
        self.config['recent_imagesets'] = recent_imagesets[:10]
        self.save_config()
        
    def set_layout_processed(self, file_path, processed=True):
        """设置布局文件的处理状态"""
        processed_layouts = self.config.get('processed_layouts', {})
        processed_layouts[file_path] = processed
        self.config['processed_layouts'] = processed_layouts
        self.save_config()
        
    def is_layout_processed(self, file_path):
        """检查布局文件是否已处理"""
        processed_layouts = self.config.get('processed_layouts', {})
        return processed_layouts.get(file_path, False) 